import 'package:casdon/modules/me/data/api/service_product_list_api.dart';
import 'package:casdon/modules/me/domain/states/service_product_list_state.dart';
import 'package:casdon/modules/me/domain/usecase/service_product_list_usecase.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class ServiceProductListNotifier
    extends AutoDisposeAsyncNotifier<List<ProductCategory>> {
  List<ProductCategory> allData = [];
  @override
  Future<List<ProductCategory>> build() async {
    if (allData.isNotEmpty) {
      return allData;
    }
    // Load once on first build so .future yields real data
    final result = await ref.read(serviceProductListUseCaseProvider).execute();
    final productList = result?.entities ?? [];
    final groupedProducts = _groupByCategory(productList);
    allData = groupedProducts.entries
        .map((entry) => ProductCategory(name: entry.key, products: entry.value))
        .toList();
    return allData;
  }

  Future<void> fetchData() async {
    if (allData.isEmpty == false) {
      state = AsyncData(allData);
      return;
    }

    if (state.isLoading) {
      return;
    }
    state = const AsyncLoading();
    try {
      final result = await ref
          .read(serviceProductListUseCaseProvider)
          .execute();
      final productList = result?.entities ?? [];
      final groupedProducts = _groupByCategory(productList);

      allData = groupedProducts.entries.map((entry) {
        return ProductCategory(name: entry.key, products: entry.value);
      }).toList();

      state = AsyncData(allData);
      return;
    } catch (e) {
      state = AsyncError(e, StackTrace.current);
      return;
    }
  }

  Map<String, List<ServiceProduct>> _groupByCategory(
    List<ServiceProduct> products,
  ) {
    return products.fold(<String, List<ServiceProduct>>{}, (map, product) {
      final categoryName = product.groupIdName;
      map.putIfAbsent(categoryName, () => []);
      map[categoryName]!.add(product);
      return map;
    });
  }
}

final serviceProductListProvider =
    AsyncNotifierProvider.autoDispose<
      ServiceProductListNotifier,
      List<ProductCategory>
    >(ServiceProductListNotifier.new);
